package org.multimedia.jolitorask.security;

import java.util.Collection;
import java.util.Hashtable;

import javax.naming.Context;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import java.net.URL;
import org.multimedia.jolitorask.client.ClientLocal;
import org.multimedia.jolitorask.client.ClientLocalHome;

public class AuthServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final String JNDI_NAME_CLIENT = "clientLocal";

	protected ClientLocal client;
	
	@SuppressWarnings("unchecked")
	protected boolean authentificate(HttpServletRequest req){
		
		// on r�cup�re le compte
		String account = req.getParameter("account");
		
		if(account==null)
			return false;
		
		Context initContext = null;
	    Hashtable env = new Hashtable(1);
	    Object beanObject = null;
	    
	    	
	    try {
	    	initContext = new javax.naming.InitialContext(env);
	    	beanObject = initContext.lookup(JNDI_NAME_CLIENT);
	    	ClientLocalHome home = (ClientLocalHome) beanObject;
			
			Collection<ClientLocal> c = home.findByLogin(account);
			
			if(c == null || c.isEmpty() ){
				return false;
			}
			
			client = c.iterator().next();
			
			// on recup�re l url
			URL url = new URL(client.getUrl());
			System.out.println(req.getHeader("Referer")+"<-");
			
			URL referrer = new URL(req.getHeader("REFERER"));
			
			// on compare
			if( !url.getHost().equals(referrer.getHost()) )
				return false;
			
	    }catch (Exception e) {
			e.printStackTrace();
	    	return false;
		}
		
		return true;
	}

	public ClientLocal getClient() {
		return client;
	}
	
}
